import Vue from 'vue';
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

import { getCodes } from "@/api/common.js";
import _ from "lodash";
async function getLang() {
	let data = await getCodes();
	// console.log("🚀 ~ getLang ~ res:", data);
	let list = data ? data : [];
	let lang = {};
	list.map((res) => {
		lang[res.code] = res.codeMap;
	});
	// console.log(lang)
	return lang;
}
async function loadLanguage() {
	const context = require.context("./languages", false, /([a-z_]+)\.js$/i);
	let list = await getLang();
	const languages = context
		.keys()
		.map((key) => ({ key, name: key.match(/([a-z_-]+)\.js$/i)[1] }))
		.reduce((languages, { key, name }) => {
			let lang;
			try {
				// 引入 element-ui 语言包
				lang = Object.assign(
					context(key).lang,
					require(`element-ui/lib/locale/lang/${name}`).default
				);
			} catch (err) {
				lang = context(key).lang;
			}
			return {
				...languages,
				[name]: lang,
			};
		}, {});
	const lang = _.merge({}, list, languages);
	// console.log(lang);
	return lang;
}

// 延迟初始化 VueI18n
export async function createI18n() {
	const messages = await loadLanguage();
	return new VueI18n({
		locale: localStorage.getItem("locale") || "zh-CN",
		fallbackLocale: "zh-CN",
		messages,
		silentTranslationWarn: true, // 去除国际化警告
	});
}